import React, { useMemo, useState } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import { Layout, UI, useThemeColors, Feedback } from '@gaozh1024/rn-toolkit';
import type { ActionSheetAction } from '@gaozh1024/rn-toolkit/lib/components/feedback/ActionSheet/ActionSheetService';

const { ActionSheet } = Feedback;

const ActionSheetTestScreen: React.FC = () => {
    const colors = useThemeColors();

    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
    });

    // 行为与样式配置
    const [cancelable, setCancelable] = useState<boolean>(true);
    const [enablePanToClose, setEnablePanToClose] = useState<boolean>(true);
    const [blocking, setBlocking] = useState<boolean>(true);
    const [cancelText, setCancelText] = useState<string>('取消');
    const [maskColor, setMaskColor] = useState<string>('rgba(0,0,0,0.45)');
    const [animationDurationStr, setAnimationDurationStr] = useState<string>('220');

    // 结果与交互
    const [lastResult, setLastResult] = useState<string>('-');
    const [clickCount, setClickCount] = useState<number>(0);

    const demoActions: ActionSheetAction[] = useMemo(() => [
        { text: '拍照', value: 'camera' },
        { text: '从相册选择', value: 'album' },
        { text: '删除（危险操作）', value: 'delete', role: 'destructive' },
        { text: '取消项（返回 false）', role: 'cancel' },
    ], []);

    const commonOptions = useMemo(() => ({
        title: '选择操作',
        actions: demoActions,
        cancelText,
        cancelable,
        enablePanToClose,
        blocking,
        maskColor,
        animationDuration: Number.isFinite(parseInt(animationDurationStr)) ? parseInt(animationDurationStr) : 220,
    }), [demoActions, cancelText, cancelable, enablePanToClose, blocking, maskColor, animationDurationStr]);

    // 基础用法：fire-and-forget 展示
    const showBasic = () => {
        ActionSheet.show(commonOptions);
    };

    // Promise 用法：等待选择结果
    const openAwaitResult = async () => {
        const v = await ActionSheet.open(commonOptions);
        setLastResult(v === false ? '取消（false）' : String(v));
    };

    // 编程取消：展示后 1.6s 自动取消
    const showThenCancel = () => {
        ActionSheet.show(commonOptions);
        setTimeout(() => ActionSheet.cancel(), 1600);
    };

    // 编程选择：展示后 1.6s 自动选择第一个 action
    const showThenChooseFirst = () => {
        ActionSheet.show(commonOptions);
        setTimeout(() => ActionSheet.choose(demoActions[0]), 1600);
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'ActionSheet 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="ActionSheetTestScreen"
        >
            {/* 开关设置 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>开关设置</UI.Text>
                    <View style={styles.row}>
                        <UI.Text variant="body2" color="textSecondary">遮罩点击取消（cancelable）</UI.Text>
                        <Switch value={cancelable} onValueChange={setCancelable} testID="switch-cancelable" />
                        <UI.Text variant="body2" color="textSecondary">下拉拖拽关闭（enablePanToClose）</UI.Text>
                        <Switch value={enablePanToClose} onValueChange={setEnablePanToClose} testID="switch-pan-close" />
                        <UI.Text variant="body2" color="textSecondary">阻塞底层交互（blocking）</UI.Text>
                        <Switch value={blocking} onValueChange={setBlocking} testID="switch-blocking" />
                    </View>
                </Layout.Card>
            </View>

            {/* 样式与动画 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>样式与动画</UI.Text>
                    <View style={styles.col}>
                        <UI.Text children={'取消按钮文案（cancelText）'} />
                        <UI.Input
                            value={cancelText}
                            onChangeText={setCancelText}
                            placeholder="取消"
                            testID="input-cancel-text"
                        />
                        <UI.Text children={'遮罩颜色（maskColor）'} />
                        <UI.Input
                            value={maskColor}
                            onChangeText={setMaskColor}
                            placeholder="rgba(0,0,0,0.45)"
                            testID="input-mask-color"
                        />
                        <UI.Text children={'动画时长（animationDuration）'} />
                        <UI.Input
                            value={animationDurationStr}
                            onChangeText={setAnimationDurationStr}
                            placeholder="220"
                            keyboardType="numeric"
                            testID="input-animation-duration"
                        />
                    </View>
                </Layout.Card>
            </View>

            {/* 基础用法 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>基础用法</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="展示（show）" onPress={showBasic} fullWidth testID="btn-show-basic" />
                        <UI.Button title="打开并等待（open）" onPress={openAwaitResult} fullWidth testID="btn-open-await" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>选择结果：</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-last-result">{lastResult}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* 编程方式控制 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>编程控制</UI.Text>
                    <UI.Text variant="caption" color="subtext" mb={8}>演示通过 API 主动取消或选择</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="展示后自动取消" variant="outline" onPress={showThenCancel} fullWidth testID="btn-show-cancel" />
                        <UI.Button title="展示后自动选择第一个" variant="outline" onPress={showThenChooseFirst} fullWidth testID="btn-show-choose-first" />
                    </View>
                </Layout.Card>
            </View>

            {/* 穿透/阻塞测试（blocking） */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>阻塞/穿透测试</UI.Text>
                    <UI.Text variant="caption" color="subtext" mb={8}>
                        当 blocking=false 时，ActionSheet 打开期间底层按钮仍可点击（overlay 不拦截事件）。
                    </UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="打开 ActionSheet" onPress={showBasic} fullWidth testID="btn-open-for-blocking" />
                        <UI.Button title="底层按钮（点我计数）" onPress={() => setClickCount((n) => n + 1)} fullWidth testID="btn-underlying" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body1" color="text" testID="text-click-count">底层点击计数：{clickCount}</UI.Text>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default ActionSheetTestScreen;